package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.emp.EmployeeCustomerDataDTO;
import com.pactera.madp.cp.api.dto.emp.EmployeeListDTO;
import com.pactera.madp.cp.api.dto.emp.EmployeeTendencyChartDTO;
import com.pactera.madp.cp.api.dto.emp.SidebarEmpDto;
import com.pactera.madp.cp.api.em.workcontact.AddWayEnum;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.clientLossManagement.ContactLossEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.employee.*;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkEmployeeStatisticMapper;
import com.pactera.madp.cp.mapper.clientLossManagement.ContactLossMapper;
import com.pactera.madp.cp.mapper.workroom.WorkRoomMapper;
import com.pactera.madp.cp.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

@Service
@AllArgsConstructor
@Slf4j
public class WorkEmployeeStatisticServiceImpl extends ServiceImpl<WorkEmployeeStatisticMapper, WorkEmployeeStatisticEntity> implements IWorkEmployeeStatisticService {

    private final IWorkContactEmployeeService workContactEmployeeService;
    private final IWorkEmployeeService workEmployeeService;
    private final IWorkContactTagService workContactTagService;
    private final IWorkContactTagPivotService workContactTagPivotService;
    private final IWorkContactService workContactService;
    private final WorkRoomMapper workRoomMapper;
    private final ContactLossMapper contactLossMapper;
    private final RemoteDeptService remoteDeptService;
    private final IWorkEmployeeService employeeService;
    private final IWorkDeptService deptService;

    @Override
    public EmployeeCustomerDataVO getCustomerData(EmployeeCustomerDataDTO dto) {
        List<WorkEmployeeStatisticEntity> statisticEntities = list(Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                .eq(WorkEmployeeStatisticEntity::getCorpId, CorpContextHolder.getCorpId())
                .le(WorkEmployeeStatisticEntity::getSynTime, dto.getEndTime() + " 23:59:59")
                .ge(WorkEmployeeStatisticEntity::getSynTime, dto.getStartTime() + " 00:00:00"));
        EmployeeCustomerDataVO customerDataVO = new EmployeeCustomerDataVO();


        AtomicInteger chatCnt = new AtomicInteger();
        AtomicInteger messageCnt = new AtomicInteger();
        AtomicInteger replyPercentage = new AtomicInteger();
        AtomicInteger avgReplyTime = new AtomicInteger();
        AtomicInteger count1 = new AtomicInteger();
        AtomicInteger count2 = new AtomicInteger();

        statisticEntities.forEach(st ->{
            if (st.getChatCnt() >0){
                count1.set(count1.get()+1);
            }
            chatCnt.set(st.getChatCnt()+chatCnt.get());
            messageCnt.set(st.getMessageCnt()+messageCnt.get());
            if (st.getAvgReplyTime() >0){
                count2.set(count2.get()+1);
            }
            replyPercentage.set(st.getReplyPercentage()+replyPercentage.get());
            avgReplyTime.set(st.getAvgReplyTime()+avgReplyTime.get());
        });

        if (!statisticEntities.isEmpty()){
            if (count2.get() >0){
                avgReplyTime.set(avgReplyTime.get() / count2.get());
            }
           if (count1.get() > 0){
               replyPercentage.set(replyPercentage.get() / count1.get());
           }

        }
        customerDataVO.setChatCnt(chatCnt.get());
        customerDataVO.setMessageCnt(messageCnt.get());
        customerDataVO.setAvgReplyTime(avgReplyTime.get());
        customerDataVO.setReplyPercentage(replyPercentage.get() / 100);
        return customerDataVO;
    }

    @Override
    public EmployeeCustomerDataVO getCustomerDataByDept(EmployeeCustomerDataDTO dto, Integer deptId, Integer wxDeptId) {
        AtomicInteger chatCnt = new AtomicInteger(0);
        AtomicInteger messageCnt = new AtomicInteger(0);
        AtomicInteger replyPercentage = new AtomicInteger(0);
        AtomicInteger avgReplyTime = new AtomicInteger(0);
        AtomicInteger count1 = new AtomicInteger(0);
        AtomicInteger count2 = new AtomicInteger(0);
        EmployeeCustomerDataVO customerDataVO = new EmployeeCustomerDataVO();
        WorkDeptEntity workDeptEntity = deptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        customerDataVO.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        customerDataVO.setName(workDeptEntity.getName());

        Set<Integer> employeeIds = getEmployees(deptId);
        if (employeeIds != null && employeeIds.size() > 0) {
            List<WorkEmployeeStatisticEntity> statisticEntities = list(Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                    .eq(WorkEmployeeStatisticEntity::getCorpId,CorpContextHolder.getCorpId())
                    .in(WorkEmployeeStatisticEntity::getEmployeeId, employeeIds)
                    .le(WorkEmployeeStatisticEntity::getSynTime, dto.getEndTime() + " 23:59:59")
                    .ge(WorkEmployeeStatisticEntity::getSynTime, dto.getStartTime() + " 00:00:00"));

            statisticEntities.forEach(st -> {
                if (st.getChatCnt() > 0) {
                    count1.set(count1.get() + 1);
                }
                chatCnt.set(st.getChatCnt() + chatCnt.get());
                messageCnt.set(st.getMessageCnt() + messageCnt.get());
                if (st.getAvgReplyTime() > 0) {
                    count2.set(count2.get() + 1);
                }
                replyPercentage.set(st.getReplyPercentage() + replyPercentage.get());
                avgReplyTime.set(st.getAvgReplyTime() + avgReplyTime.get());
            });

            if (!statisticEntities.isEmpty()) {
                if (count2.get() > 0) {
                    avgReplyTime.set(avgReplyTime.get() / count2.get());
                }
                if (count1.get() > 0) {
                    replyPercentage.set(replyPercentage.get() / count1.get());
                }

            }
        }

        customerDataVO.setChatCnt(chatCnt.get());
        customerDataVO.setMessageCnt(messageCnt.get());
        customerDataVO.setAvgReplyTime(avgReplyTime.get());
        customerDataVO.setReplyPercentage(replyPercentage.get() / 100);
        return customerDataVO;
    }

    @Override
    public EmployeeCustomerDataVO getCustomerDataByUser(EmployeeCustomerDataDTO dto, String mobile) {
        WorkEmployeeEntity entity = employeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getWxUserId, WorkEmployeeEntity::getName)
                        .eq(WorkEmployeeEntity::getMobile, mobile)
        );
        List<WorkEmployeeStatisticEntity> statisticEntities = list(Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                .eq(WorkEmployeeStatisticEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkEmployeeStatisticEntity::getEmployeeId, entity.getId())
                .le(WorkEmployeeStatisticEntity::getSynTime, dto.getEndTime()+" 23:59:59")
                .ge(WorkEmployeeStatisticEntity::getSynTime, dto.getStartTime()+" 00:00:00"));
        EmployeeCustomerDataVO customerDataVO = new EmployeeCustomerDataVO();

        AtomicInteger chatCnt = new AtomicInteger();
        AtomicInteger messageCnt = new AtomicInteger();
        AtomicInteger replyPercentage = new AtomicInteger();
        AtomicInteger avgReplyTime = new AtomicInteger();
        AtomicInteger count1 = new AtomicInteger();
        AtomicInteger count2 = new AtomicInteger();

        statisticEntities.forEach(st ->{
            if (st.getChatCnt() >0){
                count1.set(count1.get()+1);
            }
            chatCnt.set(st.getChatCnt()+chatCnt.get());
            messageCnt.set(st.getMessageCnt()+messageCnt.get());
            if (st.getAvgReplyTime() >0){
                count2.set(count2.get()+1);
            }
            replyPercentage.set(st.getReplyPercentage()+replyPercentage.get());
            avgReplyTime.set(st.getAvgReplyTime()+avgReplyTime.get());
        });

        if (!statisticEntities.isEmpty()){
            if (count2.get() > 0){
                avgReplyTime.set(avgReplyTime.get() / count2.get());
            }
            if (count1.get() > 0){
                replyPercentage.set(replyPercentage.get() / count1.get());
            }

        }
        customerDataVO.setChatCnt(chatCnt.get());
        customerDataVO.setMessageCnt(messageCnt.get());
        customerDataVO.setAvgReplyTime(avgReplyTime.get());
        customerDataVO.setReplyPercentage(replyPercentage.get() / 100);

        customerDataVO.setCode(String.valueOf(entity.getWxUserId()));
        customerDataVO.setName(entity.getName());
        return customerDataVO;
    }

    @Override
    public EmployeeStatisticsDataVO getStatisticsData(EmployeeCustomerDataDTO dto, Set<Integer> employeeIds) {
        Integer corpId = CorpContextHolder.getCorpId();
        String now = new DateTime().toDateStr();
        String start = now + " 00:00:00";
        String end = now + " 23:59:59";
        if (dto != null) {
            if (dto.getStartTime() != null)
                start = dto.getStartTime().substring(0, 10) + " 00:00:00";
            if (dto.getEndTime() != null)
                end = dto.getEndTime().substring(0, 10) + " 23:59:59";
        }
        // 成员总数
        Integer empTotal = workEmployeeService.count(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getCorpId, corpId)
                .in(WorkEmployeeEntity::getId, employeeIds)
                .lt(WorkEmployeeEntity::getCreateTime, end)
        );
        // 离职人数
        Integer empLeaveTotal = workEmployeeService.count(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId, corpId)
                        // status激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业
                        .eq(WorkEmployeeEntity::getStatus, 5)
                        .in(WorkEmployeeEntity::getId, employeeIds)
                        .lt(WorkEmployeeEntity::getCreateTime, end)
        );
        // 在职人数
        Integer empOnTotal = empTotal - empLeaveTotal;

        // 客户总数
        Integer contactTotal = workContactService.countByEmployeeIds(employeeIds, corpId, end);
        /*Integer contactTotal = workContactService.count(
                Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getCorpId, corpId)
        );*/
        // 流失客户数
        Integer contactLossTotal = contactLossMapper.selectCount(
                Wrappers.<ContactLossEntity>lambdaQuery()
                .eq(ContactLossEntity::getCorpId, corpId)
                .in(ContactLossEntity::getEmployeeId, employeeIds)/*
                .ge(ContactLossEntity::getCreateTime, start)*/
                .lt(ContactLossEntity::getLossTime, end)
        );
        // 群（客群）数量
        Integer roomTotal = workRoomMapper.selectCount(
                Wrappers.<WorkRoomEntity>lambdaQuery()
                .eq(WorkRoomEntity::getCorpId, corpId)
                .in(WorkRoomEntity::getOwnerId, employeeIds)
                .lt(WorkRoomEntity::getCreateTime, end)
        );
        EmployeeStatisticsDataVO employeeStatisticsDataVO = new EmployeeStatisticsDataVO();
        employeeStatisticsDataVO.setContactLossTotal(contactLossTotal);
        employeeStatisticsDataVO.setContactTotal(contactTotal);
        employeeStatisticsDataVO.setEmpLeaveTotal(empLeaveTotal);
        employeeStatisticsDataVO.setEmpOnTotal(empOnTotal);
        employeeStatisticsDataVO.setRoomTotal(roomTotal);
        employeeStatisticsDataVO.setEmpTotal(empTotal);
        return employeeStatisticsDataVO;
    }

    @Override
    public EmployeeStatisticsDataVO getStatisticsDatas(EmployeeCustomerDataDTO dto, Integer deptId, Integer wxDeptId) {
        EmployeeStatisticsDataVO employeeStatisticsDataVO;
        Set<Integer> employeeIds = getEmployees(deptId);
        if (employeeIds == null || employeeIds.size() == 0) {
            employeeStatisticsDataVO = new EmployeeStatisticsDataVO();
            employeeStatisticsDataVO.setContactLossTotal(0);
            employeeStatisticsDataVO.setContactTotal(0);
            employeeStatisticsDataVO.setEmpLeaveTotal(0);
            employeeStatisticsDataVO.setEmpOnTotal(0);
            employeeStatisticsDataVO.setRoomTotal(0);
            employeeStatisticsDataVO.setEmpTotal(0);
        } else {
            employeeStatisticsDataVO = getStatisticsData(dto, employeeIds);
        }
        WorkDeptEntity workDeptEntity = deptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        employeeStatisticsDataVO.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        employeeStatisticsDataVO.setName(workDeptEntity.getName());
        return employeeStatisticsDataVO;
    }

    @Override
    public EmployeeStatisticsDataVO getStatisticsDatas(EmployeeCustomerDataDTO dto, String mobile) {
        WorkEmployeeEntity entity = employeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .select(WorkEmployeeEntity::getId, WorkEmployeeEntity::getWxUserId, WorkEmployeeEntity::getName)
                .eq(WorkEmployeeEntity::getMobile, mobile)
        );
        Set<Integer> employeeIds = new HashSet<>();
        employeeIds.add(entity.getId());
        EmployeeStatisticsDataVO employeeStatisticsDataVO = getStatisticsData(dto, employeeIds);
        employeeStatisticsDataVO.setCode(entity.getWxUserId());
        employeeStatisticsDataVO.setName(entity.getName());
        return employeeStatisticsDataVO;
    }

    @Override
    public EmployeeCustomerDataXYVO getTop10Employee() {
        QueryWrapper<WorkContactEmployeeEntity> wrapper = new QueryWrapper<>();
        wrapper.select("employee_id,count(employee_id) as counts");
        wrapper.eq("corp_id",CorpContextHolder.getCorpId());
        wrapper.groupBy("employee_id");
        wrapper.orderByDesc("counts");
        wrapper.last("limit 10");
        List<Map<String, Object>> maps = workContactEmployeeService.listMaps(wrapper);

        LinkedList<EmployeeCustomerDataXYVO.XY> list = new LinkedList<>();
        AtomicReference<Integer> counts = new AtomicReference<>(0);
        maps.forEach(m ->{
            EmployeeCustomerDataXYVO.XY dataXYVO = new EmployeeCustomerDataXYVO.XY();
            WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(WorkEmployeeEntity::getId, m.get("employee_id")));
            if (entity == null){
                return;
            }
            dataXYVO.setName(entity.getName());
            dataXYVO.setCount(Integer.valueOf(m.get("counts").toString()) );
            counts.updateAndGet(v -> v + dataXYVO.getCount());
            list.add(dataXYVO);
        });
        EmployeeCustomerDataXYVO xyvo = new EmployeeCustomerDataXYVO();
        xyvo.setList(list);
        xyvo.setCounts(counts.get());
        return xyvo;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getTendencyChart(EmployeeTendencyChartDTO dto) {

        QueryWrapper<WorkEmployeeStatisticEntity> wrapper = new QueryWrapper<>();
        wrapper.select("sum(chat_cnt) as chatCnts, sum(message_cnt) as messageCnts,sum(reply_percentage) as replyPercentages,sum(avg_reply_time) as avgReplyTimes,syn_time as synTime");
        wrapper.eq("corp_id",CorpContextHolder.getCorpId());
        wrapper.le("syn_time",dto.getEndTime()+" 23:59:59");
        wrapper.ge("syn_time",dto.getStartTime()+" 00:00:00");

        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());

        if (dto.getEmployeeId() != null){
            wrapper.in("employee_id",dto.getEmployeeId());
        }
        if (dto.getDeptId() != null){
            List<WorkEmployeeEntity> list = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(WorkEmployeeEntity::getMainDepartmentId, dto.getDeptId()));
            wrapper.in("employee_id",list);
        }
        wrapper.groupBy("syn_time");
        List<Map<String, Object>> list = listMaps(wrapper);
        List<EmployeeStaticsTendencyVO> chartVOS = new LinkedList<>();

            hashList.forEach(h ->{
                EmployeeStaticsTendencyVO vo = new EmployeeStaticsTendencyVO();
                vo.setNumber(0);
                vo.setType(dto.getType());
                vo.setTime(h.toDateStr());
                for (int i = 0; i < list.size(); i++) {
                    Date time = (Date) list.get(i).get("synTime");
                    long timeTime = time.getTime();
                    if (timeTime == h.getTime()){
                         vo = new EmployeeStaticsTendencyVO();

                        QueryWrapper<WorkEmployeeStatisticEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.select("count(chat_cnt) as count1,count(avg_reply_time) as count2");
                        queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());
                        queryWrapper.le("syn_time", dto.getEndTime() + " 23:59:59");
                        queryWrapper.ge("syn_time", dto.getStartTime() + " 00:00:00");

                        if (dto.getEmployeeId() != null) {
                            queryWrapper.in("employee_id", dto.getEmployeeId());
                        }
                        if (dto.getDeptId() != null) {
                            List<WorkEmployeeEntity> lists = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                    .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                                    .eq(WorkEmployeeEntity::getMainDepartmentId, dto.getDeptId()));
                            queryWrapper.in("employee_id", lists);
                        }
                        int count1;
                        int count2;
                        {
                            queryWrapper.gt("chat_cnt", 0);
                            Map<String, Object> map = getMap(queryWrapper);
                            count1 = Integer.parseInt( map.get("count1").toString());
                        }
                        {
                            queryWrapper.gt("avg_reply_time", 0);
                            Map<String, Object> map = getMap(queryWrapper);
                            count2 = Integer.parseInt( map.get("count2").toString());
                        }


                        switch (dto.getType()){
                            case 2:
                                vo.setNumber(Integer.valueOf(list.get(i).get("messageCnts").toString()));
                                break;
                            case 3:
                                if (count1 > 1){
                                    vo.setNumber(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100 / count1);
                                }else {
                                    vo.setNumber(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100);
                                }
                                break;
                            case 4:
                                if (count2>1){
                                    vo.setNumber(Integer.parseInt(list.get(i).get("avgReplyTimes").toString()) / count2);
                                }else {
                                    vo.setNumber(Integer.valueOf(list.get(i).get("avgReplyTimes").toString()));
                                }
                                break;
                            default:
                                vo.setNumber(Integer.valueOf(list.get(i).get("chatCnts").toString()));
                                break;
                        }
                        vo.setTime(h.toDateStr());
                        vo.setType(dto.getType());
                        list.remove(i);
                        break;
                    }
                }
                chartVOS.add(vo);
        });
        return chartVOS;
    }

    /*@Override
    public List<EmployeeStaticsTendencyVO> getMessageCount(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());

        QueryWrapper<WorkEmployeeStatisticEntity> wrapper = new QueryWrapper<>();
        wrapper.select("sum(chat_cnt) as chatCnts, sum(message_cnt) as messageCnts,sum(reply_percentage) as replyPercentages,sum(avg_reply_time) as avgReplyTimes,syn_time as synTime");
        wrapper.eq("corp_id",CorpContextHolder.getCorpId());
        wrapper.lt("syn_time",dto.getEndTime()+" 23:59:59");
        wrapper.gt("syn_time",dto.getStartTime()+" 00:00:00");

        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());

        if (employeeIds != null && employeeIds.size() > 0) {
            wrapper.in("employee_id", employeeIds);
        }
        wrapper.groupBy("syn_time");
        List<Map<String, Object>> list = listMaps(wrapper);
        List<EmployeeStaticsTendencyVO> chartVOS = new LinkedList<>();

        hashList.forEach(h -> {
            EmployeeStaticsTendencyVO vo = new EmployeeStaticsTendencyVO();
            vo.setNumber(0);
            vo.setType(dto.getType());
            vo.setTime(h.toDateStr());
            if (employeeIds != null && employeeIds.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Date time = (Date) list.get(i).get("synTime");
                    long timeTime = time.getTime();
                    if (timeTime == h.getTime()){
                        vo = new EmployeeStaticsTendencyVO();

                        QueryWrapper<WorkEmployeeStatisticEntity> queryWrapper = new QueryWrapper<>();
                        queryWrapper.select("count(chat_cnt) as count1,count(avg_reply_time) as count2");
                        queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());
                        queryWrapper.le("syn_time", dto.getEndTime() + " 23:59:59");
                        queryWrapper.ge("syn_time", dto.getStartTime() + " 00:00:00");

                        if (dto.getEmployeeId() != null) {
                            queryWrapper.in("employee_id", employeeIds);
                        }
                        int count1;
                        int count2;
                        {
                            queryWrapper.gt("chat_cnt", 0);
                            Map<String, Object> map = getMap(queryWrapper);
                            count1 = Integer.parseInt( map.get("count1").toString());
                        }
                        {
                            queryWrapper.gt("avg_reply_time", 0);
                            Map<String, Object> map = getMap(queryWrapper);
                            count2 = Integer.parseInt( map.get("count2").toString());
                        }


                        switch (dto.getType()){
                            case 2:
                                vo.setNumber(Integer.valueOf(list.get(i).get("messageCnts").toString()));
                                break;
                            case 3:
                                if (count1 > 1){
                                    vo.setNumber(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100 / count1);
                                }else {
                                    vo.setNumber(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100);
                                }
                                break;
                            case 4:
                                if (count2>1){
                                    vo.setNumber(Integer.parseInt(list.get(i).get("avgReplyTimes").toString()) / count2);
                                }else {
                                    vo.setNumber(Integer.valueOf(list.get(i).get("avgReplyTimes").toString()));
                                }
                                break;
                            default:
                                vo.setNumber(Integer.valueOf(list.get(i).get("chatCnts").toString()));
                                break;
                        }
                        vo.setTime(h.toDateStr());
                        vo.setType(dto.getType());
                        list.remove(i);
                        break;
                    }
                }
            }
            chartVOS.add(vo);
        });
        return chartVOS;
    }*/

    @Override
    public List<EmployeeStaticsTendencyVO> getMessageCount(EmployeeTendencyChartDTO dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<EmployeeStaticsTendencyVO> chartVOS = new LinkedList<>();

        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        if (employeeIds == null || employeeIds.size() == 0) {
            hashList.forEach(h -> {
                EmployeeStaticsTendencyVO vo = new EmployeeStaticsTendencyVO();
                vo.setNumber(0);
                vo.setType(dto.getType());
                vo.setTime(h.toDateStr());
                chartVOS.add(vo);
            });
            return chartVOS;
        }

        QueryWrapper<WorkEmployeeStatisticEntity> wrapper = new QueryWrapper<>();
        wrapper.select("sum(chat_cnt) as chatCnts, sum(message_cnt) as messageCnts, sum(reply_percentage) as replyPercentages, sum(avg_reply_time) as avgReplyTimes, syn_time as synTime");
        wrapper.eq("corp_id", CorpContextHolder.getCorpId());
        wrapper.lt("syn_time", dto.getEndTime() + " 23:59:59");
        wrapper.ge("syn_time", dto.getStartTime() + " 00:00:00");
        wrapper.in("employee_id", employeeIds);
        wrapper.groupBy("syn_time");
        List<Map<String, Object>> list = listMaps(wrapper);

        hashList.forEach(h -> {
            EmployeeStaticsTendencyVO vo = new EmployeeStaticsTendencyVO();
            vo.setNumber(0);
            vo.setType(dto.getType());
            vo.setTime(h.toDateStr());
            inner:
            for (int i = 0; i < list.size(); i++) {
                Date time = (Date) list.get(i).get("synTime");
                long timeTime = time.getTime();
                if (timeTime == h.getTime()) {
                    switch (dto.getType()) {
                        case 1:
                            vo.setNumber(Integer.valueOf(list.get(i).get("chatCnts").toString()));
                            break inner;
                        case 2:
                            vo.setNumber(Integer.valueOf(list.get(i).get("messageCnts").toString()));
                            break inner;
                        case 3:
                            vo.setNumber(Integer.parseInt(list.get(i).get("replyPercentages").toString()));
                            break inner;
                        case 4:
                            vo.setNumber(Integer.valueOf(list.get(i).get("avgReplyTimes").toString()));
                            break inner;
                        default:
                            break inner;
                    }
                }
            }
            chartVOS.add(vo);
        });
        return chartVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getEmpTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer empTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                empTotal = workEmployeeService.count(
                        Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .in(WorkEmployeeEntity::getId, employeeIds)
                                .lt(WorkEmployeeEntity::getCreateTime, end)
                );
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(5);
            employeeStaticsTendencyVO.setNumber(empTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getEmpOnTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer empOnTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                empOnTotal = workEmployeeService.count(
                        Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                // status激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业
                                .ne(WorkEmployeeEntity::getStatus, 5)
                                .in(WorkEmployeeEntity::getId, employeeIds)
                                .lt(WorkEmployeeEntity::getCreateTime, start)
                );
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(6);
            employeeStaticsTendencyVO.setNumber(empOnTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getEmpLeaveTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer empLeaveTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                empLeaveTotal = workEmployeeService.count(
                        Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                // status激活状态: 1=已激活，2=已禁用，4=未激活，5=退出企业
                                .eq(WorkEmployeeEntity::getStatus, 5)
                                .in(WorkEmployeeEntity::getId, employeeIds)
                                .lt(WorkEmployeeEntity::getCreateTime, start)
                );
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(7);
            employeeStaticsTendencyVO.setNumber(empLeaveTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getContactTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer contactTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                contactTotal = workContactService.countByEmployeeIds(employeeIds, corpId, start);
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(8);
            employeeStaticsTendencyVO.setNumber(contactTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getContactLossTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer contactLossTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                contactLossTotal = contactLossMapper.selectCount(
                        Wrappers.<ContactLossEntity>lambdaQuery()
                                .eq(ContactLossEntity::getCorpId, corpId)
                                .in(ContactLossEntity::getEmployeeId, employeeIds)
                                .ge(ContactLossEntity::getCreateTime, start)
                                .lt(ContactLossEntity::getCreateTime, end)
                );
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(9);
            employeeStaticsTendencyVO.setNumber(contactLossTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public List<EmployeeStaticsTendencyVO> getRoomTotal(EmployeeTendencyChartDTO dto) {
        Set<Integer> employeeIds = getEmployees(dto.getDeptId());
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        Integer corpId = CorpContextHolder.getCorpId();
        List<EmployeeStaticsTendencyVO> employeeStaticsTendencyVOS = new ArrayList<>();

        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10) + " 00:00:00";
            String end = s.toDateStr().substring(0, 10) + " 23:59:59";

            Integer roomTotal = 0;
            if (employeeIds != null && employeeIds.size() != 0) {
                roomTotal = workRoomMapper.selectCount(
                        Wrappers.<WorkRoomEntity>lambdaQuery()
                                .eq(WorkRoomEntity::getCorpId, corpId)
                                .in(WorkRoomEntity::getOwnerId, employeeIds)
                                .lt(WorkRoomEntity::getCreateTime, start)
                );
            }

            EmployeeStaticsTendencyVO employeeStaticsTendencyVO = new EmployeeStaticsTendencyVO();
            employeeStaticsTendencyVO.setTime(s.toDateStr());
            employeeStaticsTendencyVO.setType(10);
            employeeStaticsTendencyVO.setNumber(roomTotal);
            employeeStaticsTendencyVOS.add(employeeStaticsTendencyVO);
        });
        return employeeStaticsTendencyVOS;
    }

    @Override
    public Page<List<EmployeeListVO>> getEmployeeList(EmployeeListDTO dto, Page page) {
        QueryWrapper<WorkEmployeeStatisticEntity> wrapper = new QueryWrapper<>();
        wrapper.select("employee_id as employeeId,sum(chat_cnt) as chatCnts, sum(message_cnt) as messageCnts,sum(reply_percentage) as replyPercentages,sum(avg_reply_time) as avgReplyTimes");
        wrapper.eq("corp_id",CorpContextHolder.getCorpId());
        wrapper.le("syn_time",dto.getEndTime()+" 23:59:59");
        wrapper.ge("syn_time",dto.getStartTime()+" 00:00:00");
        wrapper.groupBy("employee_id");
        IPage iPage = pageMaps(page, wrapper);
        List<Map<String, Object>> records = iPage.getRecords();
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());

        List<EmployeeListVO> vos = new LinkedList<>();

        records.forEach(m ->{
            EmployeeListVO vo = new EmployeeListVO();
            BeanUtil.copyProperties(m,vo);

            QueryWrapper<WorkEmployeeStatisticEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("count(chat_cnt) as count1,count(avg_reply_time) as count2");
            queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());
            queryWrapper.le("syn_time", dto.getEndTime() + " 23:59:59");
            queryWrapper.ge("syn_time", dto.getStartTime() + " 00:00:00");
            queryWrapper.eq("employee_id",vo.getEmployeeId());

            int count1;
            int count2;
            {
                queryWrapper.gt("chat_cnt", 0);
                Map<String, Object> map = getMap(queryWrapper);
                count1 = Integer.parseInt( map.get("count1").toString());
            }
            {
                queryWrapper.gt("avg_reply_time", 0);
                Map<String, Object> map = getMap(queryWrapper);
                count2 = Integer.parseInt( map.get("count2").toString());
            }
            if (count1 == 0){
                count1 = 1;
            }
            if (count2 == 0){
                count2 = 1;
            }

            vo.setAvgReplyTimes(vo.getAvgReplyTimes() / count2);
            vo.setReplyPercentages(vo.getReplyPercentages() / 100 / count1);
            WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(WorkEmployeeEntity::getId, vo.getEmployeeId()));
            if (entity == null){
                return;
            }
            vo.setEmployeeName(entity.getName());
            vo.setAvatar(entity.getAvatar());
            vos.add(vo);
        });

        SubPage subPage = new SubPage();
        subPage.setRecords(vos);
        subPage.setSize(iPage.getSize());
        subPage.setCurrent(iPage.getCurrent());
        subPage.setTotal(iPage.getTotal());
        subPage.setPages(iPage.getPages());
        return subPage;
    }

    @Override
    public EmployeeDetailsVO getDetails(Integer employeeId) {
        EmployeeDetailsVO detailsVO = new EmployeeDetailsVO();

        WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkEmployeeEntity::getId, employeeId));

        detailsVO.setEmployeeId(employeeId);
        detailsVO.setEmployeeName(entity.getName());
        detailsVO.setAvatar(entity.getAvatar());

        List<WorkContactEmployeeEntity> employeeEntities = workContactEmployeeService.list(Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                .eq(WorkContactEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkContactEmployeeEntity::getEmployeeId, employeeId));

        AtomicInteger contactAdd = new AtomicInteger();
        detailsVO.setContactCounts(employeeEntities.size());
        employeeEntities.forEach(e ->{
           if ( e.getCreateTime().equals(LocalDateTime.now())){
               contactAdd.set(contactAdd.get()+1);
           }
        });

        detailsVO.setContactAdd(contactAdd.get());
        LocalDateTime yesterday = LocalDateTime.now().plusDays(-1);
        DateTimeFormatter pattern =  DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter pattern2 =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String yesterdayy = pattern.format(yesterday);
        String startTime = yesterdayy + " 00:00:00";
        String endTime = yesterdayy + " 23:59:59";
        WorkEmployeeStatisticEntity employeeStatisticEntity = getOne(Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                .eq(WorkEmployeeStatisticEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkEmployeeStatisticEntity::getEmployeeId, employeeId)
                .ge(WorkEmployeeStatisticEntity::getSynTime, LocalDateTime.parse(startTime,pattern2))
                .le(WorkEmployeeStatisticEntity::getSynTime, LocalDateTime.parse(endTime,pattern2)));

        detailsVO.setChatCnts(employeeStatisticEntity.getChatCnt());
        detailsVO.setMessageCnts(employeeStatisticEntity.getMessageCnt());
        detailsVO.setAvgReplyTimes(employeeStatisticEntity.getAvgReplyTime());
        detailsVO.setReplyPercentages(employeeStatisticEntity.getReplyPercentage() / 100);

        return detailsVO;
    }

    @Override
    public List<EmployeeContactListVO> getContactList(Integer employeeId) {
        List<EmployeeContactListVO> voS = new LinkedList<>();
        List<WorkContactEmployeeEntity> workContactEmployeeEntities = workContactEmployeeService.list(Wrappers.<WorkContactEmployeeEntity>lambdaQuery()
                .eq(WorkContactEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                .eq(WorkContactEmployeeEntity::getEmployeeId, employeeId));
        workContactEmployeeEntities.forEach(w ->{
            EmployeeContactListVO vo = new EmployeeContactListVO();
            vo.setContactId(w.getContactId());
            DateTimeFormatter pattern =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            vo.setCreateTime(pattern.format(w.getCreateTime()));
            vo.setOldTime(null);
            vo.setAddWay(w.getAddWay());
            vo.setAddWayText(AddWayEnum.getByCode(w.getAddWay()));


            List<WorkContactTagPivotEntity> tagPivotEntities = workContactTagPivotService.list(Wrappers.<WorkContactTagPivotEntity>lambdaQuery()
                    .eq(WorkContactTagPivotEntity::getEmployeeId, employeeId)
                    .eq(WorkContactTagPivotEntity::getContactId, w.getContactId()));
            List<String> list = new LinkedList<>();
            tagPivotEntities.forEach(t ->{
                WorkContactTagEntity tagEntity = workContactTagService.getOne(Wrappers.<WorkContactTagEntity>lambdaQuery()
                        .eq(WorkContactTagEntity::getCorpId,CorpContextHolder.getCorpId())
                        .eq(WorkContactTagEntity::getId, t.getContactTagId()));
                if (tagEntity != null){
                    list.add(tagEntity.getName());
                }
            });
            vo.setTags(list);

            WorkContactEntity workContactEntity = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .eq(WorkContactEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(WorkContactEntity::getId, w.getContactId()));

            vo.setName(workContactEntity.getName());
            vo.setAvatar(workContactEntity.getAvatar());

            vo.setContactGrade(0);
            vo.setContactIntegral(0);

            voS.add(vo);
        });
        return voS;
    }

    @Override
    public Page<EmployeeTendencyChartVO> getPageList(EmployeeTendencyChartDTO dto, Page page) {
        QueryWrapper<WorkEmployeeStatisticEntity> wrapper = new QueryWrapper<>();
        wrapper.select("sum(chat_cnt) as chatCnts, sum(message_cnt) as messageCnts,sum(reply_percentage) as replyPercentages,sum(avg_reply_time) as avgReplyTimes,syn_time as synTime");
        wrapper.eq("corp_id",CorpContextHolder.getCorpId());
        wrapper.le("syn_time",dto.getEndTime()+" 23:59:59");
        wrapper.ge("syn_time",dto.getStartTime()+" 00:00:00");

        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());

        if (dto.getEmployeeId() != null){
            wrapper.in("employee_id",dto.getEmployeeId());
        }
        if (dto.getDeptId() != null){
            List<WorkEmployeeEntity> list = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId,CorpContextHolder.getCorpId())
                    .eq(WorkEmployeeEntity::getMainDepartmentId, dto.getDeptId()));
            wrapper.in("employee_id",list);
        }
        wrapper.groupBy("syn_time");
        List<Map<String, Object>> list = listMaps(wrapper);
        List<EmployeeTendencyChartVO> chartVOS = new LinkedList<>();

        for (DateTime h : hashList) {
            EmployeeTendencyChartVO chartVO = new EmployeeTendencyChartVO();
            chartVO.setChatCnts(0);
            chartVO.setMessageCnts(0);
            chartVO.setReplyPercentages(0);
            chartVO.setAvgReplyTimes(0);
            chartVO.setSynTime(DateUtil.formatDate(h));
            for (int i = 0; i < list.size(); i++) {
                Date time = (Date) list.get(i).get("synTime");
                DateTime dateTime = DateUtil.beginOfDay(time);
                long timeTime = dateTime.getTime();
                if (timeTime == h.getTime()) {
                    chartVO = new EmployeeTendencyChartVO();

                    QueryWrapper<WorkEmployeeStatisticEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("count(chat_cnt) as count1,count(avg_reply_time) as count2");
                    queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());
                    queryWrapper.le("syn_time", dto.getEndTime() + " 23:59:59");
                    queryWrapper.ge("syn_time", dto.getStartTime() + " 00:00:00");

                    if (dto.getEmployeeId() != null) {
                        queryWrapper.in("employee_id", dto.getEmployeeId());
                    }
                    if (dto.getDeptId() != null) {
                        List<WorkEmployeeEntity> lists = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                                .eq(WorkEmployeeEntity::getMainDepartmentId, dto.getDeptId()));
                        queryWrapper.in("employee_id", lists);
                    }
                    int count1;
                    int count2;
                    {
                        queryWrapper.gt("chat_cnt", 0);
                        Map<String, Object> map = getMap(queryWrapper);
                        count1 = Integer.parseInt( map.get("count1").toString());
                    }
                    {
                        queryWrapper.gt("avg_reply_time", 0);
                        Map<String, Object> map = getMap(queryWrapper);
                        count2 = Integer.parseInt( map.get("count2").toString());
                    }
                    chartVO.setChatCnts(Integer.valueOf(list.get(i).get("chatCnts").toString()));
                    chartVO.setMessageCnts(Integer.valueOf(list.get(i).get("messageCnts").toString()));
                    if (count1 > 1) {
                        chartVO.setReplyPercentages(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100 / count1);
                    } else {
                        chartVO.setReplyPercentages(Integer.parseInt(list.get(i).get("replyPercentages").toString()) / 100);
                    }

                    if (count2 > 1) {
                        chartVO.setAvgReplyTimes(Integer.parseInt(list.get(i).get("avgReplyTimes").toString()) / count2);
                    } else {
                        chartVO.setAvgReplyTimes(Integer.valueOf(list.get(i).get("avgReplyTimes").toString()));
                    }
                    chartVO.setSynTime(DateUtil.formatDate(h));
                    list.remove(i);
                    break;
                }
            }
            chartVOS.add(chartVO);
        }

        if (dto.getSort() == null || dto.getType() == null){
            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getSynTime).reversed());
        }else {
            switch (dto.getSort()){
                case 0:
                    switch (dto.getType()){
                        case 2:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getChatCnts));
                            break;
                        case 3:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getMessageCnts));
                            break;
                        case 4:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getReplyPercentages));
                            break;
                        case 5:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getAvgReplyTimes));
                            break;
                        default:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getSynTime));
                            break;
                    }
                    break;
                case 1:
                    switch (dto.getType()){
                        case 2:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getChatCnts).reversed());
                            break;
                        case 3:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getMessageCnts).reversed());
                            break;
                        case 4:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getReplyPercentages).reversed());
                            break;
                        case 5:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getAvgReplyTimes).reversed());
                            break;
                        default:
                            chartVOS.sort(Comparator.comparing(EmployeeTendencyChartVO::getSynTime).reversed());
                            break;
                    }
                    break;
            }
        }

        Page<EmployeeTendencyChartVO> split = PageUtil.split(chartVOS, (int) page.getCurrent(), (int) page.getSize());
        return split;
    }

    @Override
    public List<SidebarEmpTendencyVo> contactAdd(Integer employeeId, SidebarEmpDto dto) {
        List<DateTime> hashList = getDetHashList(dto.getStartTime(), dto.getEndTime());
        List<SidebarEmpTendencyVo> empTendencyVos = new ArrayList<>();
        List<WorkEmployeeStatisticEntity> list = this.list(
                Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                .select(WorkEmployeeStatisticEntity::getNewContactCnt, WorkEmployeeStatisticEntity::getSynTime)
                .eq(WorkEmployeeStatisticEntity::getEmployeeId, employeeId)
                .ge(WorkEmployeeStatisticEntity::getSynTime, dto.getStartTime())
                .lt(WorkEmployeeStatisticEntity::getSynTime, dto.getEndTime())
        );
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10);
            SidebarEmpTendencyVo empTendencyVo = new SidebarEmpTendencyVo();
            empTendencyVo.setTime(s.toDateStr());
            empTendencyVo.setNumber(0L);
            inner:
            for (WorkEmployeeStatisticEntity entity : list) {
                if (start.equals(entity.getSynTime().format(fmt))) {
                    empTendencyVo.setNumber(entity.getNewContactCnt().longValue());
                    break inner;
                }
            }
            empTendencyVos.add(empTendencyVo);
        });
        return empTendencyVos;
    }

    @Override
    public List<SidebarEmpTendencyVo> contactAdd(Integer employeeId, Integer dateType) {
        DateTime selectEnd = DateUtil.beginOfDay(DateUtil.date());
        DateTime selectStart = null;
        // dateType == 1，查近七日数据；否则查近30日数据
        if (dateType != null && dateType == 1) {
            selectStart = DateUtil.offsetDay(selectEnd, -7);
        } else {
            selectStart = DateUtil.offsetDay(selectEnd, -30);
        }

        List<SidebarEmpTendencyVo> empTendencyVos = new ArrayList<>();
        List<WorkEmployeeStatisticEntity> list = this.list(
                Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                        .select(WorkEmployeeStatisticEntity::getNewContactCnt, WorkEmployeeStatisticEntity::getSynTime)
                        .eq(WorkEmployeeStatisticEntity::getEmployeeId, employeeId)
                        .ge(WorkEmployeeStatisticEntity::getSynTime, selectStart)
                        .lt(WorkEmployeeStatisticEntity::getSynTime, selectEnd)
        );
        List<DateTime> hashList = getDetHashList(DateUtil.formatDateTime(DateUtil.date(selectStart)), DateUtil.formatDateTime(DateUtil.date(DateUtil.offsetDay(selectEnd, -1))));
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        hashList.forEach(s -> {
            String start = s.toDateStr().substring(0, 10);
            SidebarEmpTendencyVo empTendencyVo = new SidebarEmpTendencyVo();
            empTendencyVo.setTime(s.toDateStr());
            empTendencyVo.setNumber(0L);
            inner:
            for (WorkEmployeeStatisticEntity entity : list) {
                if (start.equals(entity.getSynTime().format(fmt))) {
                    empTendencyVo.setNumber(entity.getNewContactCnt().longValue());
                    break inner;
                }
            }
            empTendencyVos.add(empTendencyVo);
        });
        return empTendencyVos;
    }

    /**
     * 获取两个日期中的所有日期,并转换为表后缀
     *
     * @param begin 格式:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
     * @param end   格式:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
     * @return 格式:MM_dd
     */
    public static List<DateTime> getDetHashList(String begin, String end) {
        List<String> hashList = new ArrayList<>();
        String btime = begin.substring(0, 10);//yyyy-MM-dd
        String etime = end.substring(0, 10);

        Date bDate = DateUtil.parse(btime, DatePattern.NORM_DATE_PATTERN);//yyyy-MM-dd
        Date eDate = DateUtil.parse(etime, DatePattern.NORM_DATE_PATTERN);
        List<DateTime> dateList = DateUtil.rangeToList(bDate, eDate, DateField.DAY_OF_YEAR);//创建日期范围生成器
//        String hash = null;
//        for (DateTime dt : dateList) {
//            hash = dt.toString().replaceAll("-", "_").substring(5, 10);
//            hashList.add(hash);
//        }
        return dateList;
    }

    @Override
    public Integer contactEffectiveYesterday(Integer employeeId) {
        DateTime yesterDay = DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -1));
        WorkEmployeeStatisticEntity entity = this.getOne(
                Wrappers.<WorkEmployeeStatisticEntity>lambdaQuery()
                        .select(WorkEmployeeStatisticEntity::getChatCnt)
                        .eq(WorkEmployeeStatisticEntity::getSynTime, yesterDay)
                        .eq(WorkEmployeeStatisticEntity::getDelFlag, 0)
                        .eq(WorkEmployeeStatisticEntity::getEmployeeId, employeeId)
        );
        return entity == null ? 0 : entity.getChatCnt();
    }

    private Set<Integer> getEmployees(Integer deptId) {
        R r = remoteDeptService.getDeptsAndUsers(deptId);
        log.info("r:{}",r);
        Map<String, Object> data = (Map) r.getData();
        List<Integer> wxDeptIds = (List<Integer>) data.get("wxDeptIds");
        List<String> userMobiles = (List<String>) data.get("userMobiles");
        return employeeService.getEmployeeIds(wxDeptIds, userMobiles);
    }

}
